package com.lynch.mp3.service;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.Queue;

import android.app.Service;
import android.content.Intent;
import android.media.MediaPlayer;
import android.net.Uri;
import android.os.Environment;
import android.os.Handler;
import android.os.IBinder;

import com.lynch.lrc.LrcProcessor;
import com.lynch.model.Mp3Info;
import com.lynch.mp3.AppConstant;

public class PlayerService extends Service {
	
	private MediaPlayer mediaPlayer=null;
	private boolean isPlaying=false;
	private boolean isPause=false;
	private boolean isReleased=false;
	
	/**更新歌词需要的变量*/
	private ArrayList<Queue> queues=null;
	private Handler handler=new Handler();
	private UpdateTimeCallback updateTimeCallback=null;
	private long begin=0;
	private long nextTimeMill=0;
	private long currentTimeMill=0;
	private String message=null;
	private long pauseTimeMills=0;
	

	@Override
	public IBinder onBind(Intent arg0) {
		return null;
	}
	
	class UpdateTimeCallback implements Runnable{
		
		ArrayList<Queue> queues=null;
		Queue times;
		Queue messages;
		
		public UpdateTimeCallback(ArrayList<Queue> queues){
			System.out.println("进入回调函数前");
			System.out.println(queues.size());
			System.out.println(queues.size());
			this.queues=queues;
			times=queues.get(0);
			messages=queues.get(1);
			System.out.println("进入回调函数后");
		}
		
		@Override
		public void run() {
			
			long offeset=System.currentTimeMillis()-begin;
			//System.out.println(offeset);
			if (currentTimeMill==0) {
				nextTimeMill=(Long) times.poll();
				message=(String) messages.poll();
				System.out.println("歌词是是----->"+message);
			}
			if (offeset>=nextTimeMill) {
				Intent intent=new Intent();
				intent.setAction(AppConstant.LRC_MESSAGE_ACTION);
				intent.putExtra("lrcMessage", message);
				sendBroadcast(intent);
				message=(String) messages.poll();
				nextTimeMill=(Long) times.poll();
			}
			currentTimeMill+=10;
			handler.postDelayed(updateTimeCallback, 10);
		}
	}

	@Override
	public int onStartCommand(Intent intent, int flags, int startId) {
		
		Mp3Info mp3Info = (Mp3Info)intent.getSerializableExtra("mp3Info");
		int MSG = intent.getIntExtra("MSG", 0);
		if(mp3Info!=null){
			if(MSG == AppConstant.PlayerMsg.PLAY_MSG){
				play(mp3Info);
			}
		}else {
			if (MSG == AppConstant.PlayerMsg.PAUSE_MSG) {
				pause();
			} else if (MSG == AppConstant.PlayerMsg.STOP_MSG) {
				stop();
			}
		}
		return super.onStartCommand(intent, flags, startId);
	}

	private void play(Mp3Info mp3Info) {
		
		if (!isPlaying) {
			prepareLrc(mp3Info.getLrcName());
			begin=System.currentTimeMillis();
			handler.postDelayed(updateTimeCallback, 5);
			String path = getMp3Path(mp3Info);
			mediaPlayer = MediaPlayer.create(this, Uri.parse("file://"+path));
			mediaPlayer.setLooping(false);
			mediaPlayer.start();
			isPlaying = true;
			isReleased = false;
		}
	}
	
	private void pause() {
		
		if (mediaPlayer != null) {
			if (!isReleased) {
				if (!isPause) {
					handler.removeCallbacks(updateTimeCallback);
					pauseTimeMills=System.currentTimeMillis();
					mediaPlayer.pause();
					isPause=true;
					isPlaying=true;
				} else {
					handler.postDelayed(updateTimeCallback,5);
					begin=System.currentTimeMillis()-pauseTimeMills+begin;
					mediaPlayer.start();
					isPause=false;
				}
			} 
		} 
	}
	
	private void stop() {
		
		if(mediaPlayer != null){
			if (isPlaying) {
				if (!isReleased) {
					mediaPlayer.stop();
					mediaPlayer.release();
					handler.removeCallbacks(updateTimeCallback);
					isReleased=true;
				}
				isPlaying=false;
			}
		}
	}

	
	private String getMp3Path(Mp3Info mp3Info) {
		
		String sdCardRootString = Environment.getExternalStorageDirectory().getAbsolutePath();
		String path = sdCardRootString+File.separator+"myMp3"+File.separator+mp3Info.getMp3Name();
		return path;
	}
	
	private void prepareLrc(String lrcName) {
		
		System.out.println("歌词的名字是----=》"+lrcName);
		System.out.println("歌词文件路径是---》"+Environment.getExternalStorageDirectory().getAbsolutePath()+File.separator+
					"myMp3"+File.separator+lrcName);
		try {
			InputStream inputStream = new FileInputStream(
					Environment.getExternalStorageDirectory().getAbsolutePath()+File.separator+
					"myMp3"+File.separator+lrcName);
			LrcProcessor lrcProcessor = new LrcProcessor();
			System.out.println("准备开始解析歌词");
			queues = lrcProcessor.process(inputStream);
			System.out.println("解析歌词完毕");
			updateTimeCallback = new UpdateTimeCallback(queues);
			System.out.println("进入回调完事");
			begin = 0;
			currentTimeMill = 0;
			nextTimeMill = 0;
		} catch (FileNotFoundException e) {
			e.printStackTrace();
		}
	}
}
